angular.module('sort-modal',[])
.service 'SortModal',($ionicModal,$rootScope,$localStorage,$http,$ionicPopup,userData,orderInfo,$ionicHistory) ->
    $scope = $rootScope.$new()
    checkSort=undefined
    cacheSortToLocal=(data)->
        sorts=[]
        _.each data,(fsort)->
            fData={
                id:fsort.firstsortid
                name:fsort.firstsortname
                order:fsort.sortorder
                childs:[]
            }
            if fsort.childsort?.length>0
                _.each fsort.childsort,(ssort)->
                    sData={
                        id:ssort.secondsortid
                        name:ssort.secondsortname
                        order:fsort.sortorder
                    }
                    fData.childs.push sData
            sorts.push fData
        $scope.sorts=sorts
    $scope.choose=(sort,i,j)->
        _.each $scope.sorts,(fsort)->
            if fsort.childs?.length>0
                _.each fsort.childs,(ssort)->
                    ssort.checked=false
            fsort.checked=false
        sort.checked=true
        sort.i = i
        sort.j = j
        checkSort=sort
        console.log checkSort
    $scope.checkSort=()->
        $localStorage.checkSort=checkSort
        console.log $localStorage.checkSort
        $scope.hideModal()
    $scope.hideModal=()->
        $scope.modal.hide()
        _.delay( ->
            $scope.modal.remove()
        ,500)
    showModal:() ->
        $ionicModal.fromTemplateUrl('templates/sort-manage/sort-modal.html',{
            scope:$scope
            animation: 'slide-in-up'
        }).then (modal) ->
            $scope.modal = modal
            $scope.modal.show()
            $http.get '/updshop/',params:{action:'productsort',userid:userData.getToken()}
            .success (resp) ->
                console.log resp
                if resp.status == '0'
                    cacheSortToLocal(resp.body)
    clearChecksort: ->
        $localStorage.checkSort = undefined
